<template>
  <view class="wrapper" :class="isPad ? `pad` : `other`">
    <view class="wrapper-main">
      <view class="tabbar">
        <view class="tab-list">
          <template v-for="(value, key) in dataList">
            <view class="tab-item"
                  v-if="value.isShow"
                  :class="key == currentTabIndex ? `tab-item-${key+1} current` : `tab-item-${key+1}`"
                  @click="handleTab(key)">
            </view>
          </template>
        </view>
      </view>
      <view class="button" @click="handlePreview"></view>
      <!--<view class="button" @click="handlePrint"></view>-->
      <view class="content">
        <view class="selection">
          <scroll-view class="scroll-list" scroll-y v-if="dataList[currentTabIndex]">
            <template v-for="(value, key) in dataList[currentTabIndex].list">
              <view class="scroll-item"
                    :class="value.selected ? `scroll-item-${key+1} selected` : `scroll-item-${key+1}`"
                    :id="`s${value.id}`"
                    @click="handleSelect(value)">
                <!--<view>{{value.name}}</view>-->
                <!--<image
                    :src="value.image"
                    :alt="value.name"></image>-->
                <view :style="`background-image:url(${value.image})`"
                      :class="1 ? `item-image item-image-${value.catId}` : `item-image item-image-${value.catId}`"></view>
              </view>
            </template>
          </scroll-view>
        </view>
        <view class="preview">
          <template v-for="(value, key) in previewList">
            <view class="preview-item"
                  v-if="value.selected"
                  :style="'z-index:' + value.zIndex">
              <image
                  :src="value.image"
                  :alt="value.name"></image>
            </view>
          </template>
          <canvas canvas-id="previewCanvas" ref="previewCanvas" class="canvas" v-if="!showDialog"></canvas>
          <view class="preview-gender"
                :class="gender == 37 ? `preview-gender-2` : `preview-gender-1`"
                @click="switchGender"></view>
        </view>
      </view>
      <view class="dialog" v-if="false">
        <view class="dialog-mask" @click="closeDialog"></view>
        <view class="dialog-main">
          <view class="dialog-content">
            <image :src="image"></image>
          </view>
          <view class="dialog-button">
            <button @click="closeDialog">关闭</button>
            <button type="primary" @click="saveImage">保存到打印相册</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import {mapGetters} from 'vuex'
  import _findIndex from 'lodash/findIndex'
  import _sortBy from 'lodash/sortBy'
  import {pathToBase64, base64ToPath} from 'image-tools'
  // import Memobird from '@/common/memobird'

  export default {
    data() {
      return {
        systemInfo: {},
        isPad: true,
        currentTabIndex: 0,
        previewList: [],
        gender: 37,
        templateImage: require('@/static/template-bg.jpg'),
        // templateImage: 'https://m.360buyimg.com/imagetools/jfs/t1/70635/21/5844/149672/5d3e557cE7cbed930/e8eebaed05a6bca0.jpg',
        image: '',
        showDialog: false,
        memobird: {
          ak: '1694725394af49b98eff10c218e351ad',
          memobirdID: '759b72d6b54af51d',
          useridentifying: 'mumu',
        },
      }
    },
    async onLoad() {
      this.systemInfo = uni.getSystemInfoSync()
      this.isPad = /pad/gi.test(this.systemInfo.model)
      // #ifdef MP-WEIXIN
      // this.memobird = new Memobird({
      //   ak: '1694725394af49b98eff10c218e351ad',
      //   memobirdID: '759b72d6b54af51d',
      //   useridentifying: 'mumu',
      // })
      // await this.memobird.init()
      // await this.memobird.printText('memobird is ready')
      // #endif
    },
    async onReady() {
      this.dataList.map(item => {
        item.list.map(value => {
          if (value.selected) this.previewList.push(value)
          return value
        })
        return item
      })
    },
    computed: {
      ...mapGetters({
        dataList: 'data_list'
      })
    },
    methods: {
      /**
       * TAB切换
       *
       * @param index
       */
      handleTab(index) {
        this.currentTabIndex = index
      },
      /**
       * 选择素材
       *
       * @param value
       */
      handleSelect(value) {
        console.log(value)
        value.selected = !value.selected
        const index = _findIndex(this.previewList, {zIndex: value.zIndex})
        if (index == -1) {
          this.previewList.push(value)
        } else {
          if (value.id != this.previewList[index].id) {
            this.previewList[index].selected = false
            this.$set(this.previewList, index, value)
          }
        }
      },
      /**
       * 切换性别
       */
      switchGender() {
        // id36:男
        // id37:女
        const index = _findIndex(this.previewList, {gender: -1})
        const currentGender = this.previewList[index].id
        const maleIndex = _findIndex(this.dataList[6].list, {id: 36})
        const femaleIndex = _findIndex(this.dataList[6].list, {id: 37})
        switch (currentGender) {
          case 36:
            this.handleSelect(this.dataList[6].list[femaleIndex])
            this.gender = 37
            break;
          case 37:
            this.handleSelect(this.dataList[6].list[maleIndex])
            this.gender = 36
            break;
        }
      },
      /**
       * 读取图片并转化为临时路径
       *
       * @param image
       * @returns {Promise<*>}
       */
      async saveImageAsFilePath(image) {
        let item = {image}
        if ((/^http/).test(item.image)) {
          (await uni.getImageInfo({
            src: item.image,
          })).map(info => {
            if (info && info.path) {
              item.imagePath = info.path
            }
          })
        } else {
          item.imagePath = await base64ToPath(item.image)
        }
        return item.imagePath
      },
      /**
       * 生成预览
       *
       * @returns {Promise<void>}
       */
      async handlePreview() {
        uni.showLoading({title: '生成中'})

        this.previewList = _sortBy(this.previewList, 'zIndex')
        console.log(this.previewList)

        this.showDialog = false
        const ctx = uni.createCanvasContext('previewCanvas')
        ctx.drawImage(this.templateImage, 0, 0, 998 / this.systemInfo.pixelRatio, 2334 / this.systemInfo.pixelRatio)
        for (let i = 0, item; i < this.previewList.length; i++) {
          item = this.previewList[i]
          if (item.selected) {
            item.imagePath = await this.saveImageAsFilePath(item.image)
            console.log(item.imagePath)

            ctx.drawImage(item.imagePath, 100 / this.systemInfo.pixelRatio, 510 / this.systemInfo.pixelRatio, 820 / this.systemInfo.pixelRatio, 1080 / this.systemInfo.pixelRatio)

          }
        }

        ctx.draw(false, () => {
          uni.showLoading({title: '生成成功'})
          uni.canvasToTempFilePath({
            canvasId: 'previewCanvas',
            success: async ({tempFilePath}) => {
              this.showDialog = true
              this.image = tempFilePath

              await this.saveImage()

              // #ifdef MP-WEIXIN
              await this.printImage()
              // #endif

            },
            error: () => {
              uni.hideLoading()
              uni.showToast({title: '生成失败', duration: 3000})
            },
          })
        })
      },
      /**
       * 关闭预览对话框
       */
      closeDialog() {
        this.showDialog = false
        uni.hideLoading()
      },
      /**
       * 保存图片到本地相册
       */
      async saveImage() {
        return new Promise((resolve, reject) => {
          uni.showLoading({title: '保存中'})
          uni.saveImageToPhotosAlbum({
            filePath: this.image,
            success: errMsg => {
              uni.showToast({title: '保存成功', duration: 2000})
              resolve()
            },
            error: () => {
              uni.showToast({title: '保存失败', duration: 3000})
              reject()
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        })
      },
      /**
       * 打印图片
       *
       * @returns {Promise<void>}
       */
      async printImage() {
        uni.showToast({title: '请到相册打印', duration: 5000})
        // uni.showLoading({title: '正在打印'})
        // const printcontentid = await this.memobird.printImage(await pathToBase64(this.image))
        // let printflag = await this.memobird.watch(printcontentid)
        // uni.hideLoading()
        // if (printflag == 1) {
        //   uni.showToast({title: '打印成功', duration: 3000})
        // } else {
        //   uni.showToast({title: '打印失败，稍后再试', duration: 3000})
        // }
      },
    }
  }

</script>

<style scoped lang="scss">
  .pad{
    position:fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
  }

  .wrapper-main{
    position:relative;
    /*width:2224px;*/
    height:1668px;
    width:100%;
    overflow:hidden;
    background:url(~@/static/bg.jpg) repeat;
    .tabbar{
      position:absolute;
      /*left:105px;*/
      left:50%;
      bottom:1235px;
      z-index:2;
      width:1600px;
      margin-left:-1010px;
      .tab-list{
        width:1600px;
        height:205px;
        display:flex;
        flex-direction:row;
        .tab-item{
          position:relative;
          top:45px;
          margin-left:-20px;
          width:280px;
          height:160px;
          background-size:contain;
          background-position:0 0;
          background-repeat:no-repeat;
          @for $i from 0 through 5{
            &.tab-item-#{$i+1}{
              z-index:#{6-$i};
              background-image:url(~@/static/tab/tab-#{$i+1}.png);
            }
          }
          @for $i from 0 through 5{
            &.tab-item-#{$i+1}{
              &.current{
                background-image:url(~@/static/tab/tab-#{$i+1}-selected.png);
              }
            }
          }
          &.current{
            top:0;
            width:380px;
            height:205px;
            z-index:7;
          }
          .name{
            font-size:60px;
            font-family:"微软雅黑", "黑体", "宋体", Helvetica, Verdana, sans-serif;
            font-weight:bold;
          }
        }
      }
    }
    .button{
      position:absolute;
      right:45px;
      bottom:1272px;
      z-index:2;
      width:442px;
      height:231px;
      background:url(~@/static/button-print.png) 0 0 no-repeat;
      background-size:contain;
    }
    .content{
      position:absolute;
      bottom:20px;
      left:50%;
      margin-left:-1068.5px;
      width:2137px;
      height:1232px;
      background:url(https://m.360buyimg.com/imagetools/jfs/t1/65089/18/5491/83719/5d3a8263E12d0ad2d/553fae4bb14d2e5f.jpg) 0 0 no-repeat;
      background-size:contain;
      .selection{
        position:absolute;
        left:85px;
        top:85px;
        width:1070px;
        height:1080px;
        overflow:hidden;
        .scroll-list{
          height:1080px;
          .scroll-item{
            position:relative;
            display:block;
            float:left;
            margin:7px;
            width:312px;
            height:312px;
            background:#f9f9f9;
            border:10px solid #000;
            border-radius:30px;
            overflow:hidden;
            &.selected:after{
              content:" ";
              width:119px;
              height:121px;
              background:url(~@/static/selected.png) 0 0 no-repeat;
              background-size:contain;
              position:absolute;
              bottom:10px;
              right:10px;
            }
            image,
            .item-image{
              width:312px;
              height:312px;
            }
            .item-image{
              background-repeat:no-repeat;
              background-position:0px 0px;
              background-size:100% 100%;
            }
            .item-image-1{
              background-position:-110px -50px;
              background-size:170%;
            }
            .item-image-2{
              background-position:0px 0px;
              background-size:100%;
            }
            .item-image-3{
              background-position:-120px -120px;
              background-size:180%;
            }
            .item-image-4{
              background-position:-180px -240px;
              background-size:220%;
            }
            .item-image-5{
              background-position:-120px -80px;
              background-size:180%;
            }
            .item-image-8{
              background-position:0px 0px;
              background-size:100%;
            }
            .item-image-9{
              background-position:0px 0px;
              background-size:100%;
            }
            .item-image-10{
              background-position:-20px 100px;
              background-size:120%;
            }
          }
        }
      }
      .preview{
        position:absolute;
        right:85px;
        top:80px;
        width:820px;
        height:1080px;
        overflow:hidden;
        .preview-item{
          position:absolute;
          left:0;
          top:0;
          image{
            width:820px;
            height:1080px;
          }
        }
      }
      .canvas{
        position:absolute;
        left:9999px;
        top:9999px;
        z-index:-1;
        width:998px;
        height:2334px;
      }
      .preview-gender{
        position:absolute;
        right:0px;
        bottom:0px;
        width:253px;
        height:140px;
        background:url(~@/static/qunzi.png) 0 0 no-repeat;
        background-size:contain;
        z-index:999;
        &.preview-gender-1{
          background-image:url(~@/static/kuzi.png);
        }
        &.preview-gender-2{
          background-image:url(~@/static/qunzi.png);
        }
      }
    }
    .dialog{
      position:fixed;
      left:0;
      top:0;
      width:100%;
      height:100%;
      z-index:20;
      .dialog-mask{
        position:absolute;
        left:0;
        top:0;
        width:100%;
        height:100%;
        background:rgba(0, 0, 0, .5);
      }
      .dialog-main{
        position:absolute;
        left:50%;
        margin-left:-499px;
        top:0;
        width:998px;
        height:1668px;
        overflow:hidden;
        background:#fff;
        .dialog-content{
          width:998px;
          height:1528px;
          overflow-y:scroll;
          image,
          .canvas{
            width:998px;
            height:2334px;
          }
        }
        .dialog-button{
          position:absolute;
          left:0;
          bottom:20px;
          width:998px;
          height:100px;
          display:flex;
          flex-direction:row;
          justify-content:space-around;
          button{
            width:400px;
            height:100px;
            line-height:100px;
            margin:0 20px;
            text-align:center;
          }
        }
      }
    }
    .uni-view-scroll::-webkit-scrollbar-thumb{
      border-radius:10px;
      -webkit-box-shadow:inset 0 0 6px rgba(0, 0, 0, .3);
      background-color:#000;
    }
  }


</style>
